package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.autoconfig.template.HuanXinTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.db.*;
import com.tanhua.model.dto.RecommendUserDto;
import com.tanhua.model.vo.NearUserVo;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.TodayBest;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @auther : 白月尘
 * @date : 17:43  2021/10/18
 */
@Service
public class TanhuaService {
    @DubboReference
    private RecommendUserApi recommendUserApi;
    @Autowired
    private HuanXinTemplate huanXinTemplate;
    @DubboReference
    private UserInfoApi userInfoApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private UserLocationApi userLocationApi;
    @DubboReference
    private VisitorsApi visitorsApi;

    public PageResult recommendation(RecommendUserDto dto) {
        List<RecommendUser> list = recommendUserApi.findAll(UserHolder.getUserId(), dto.getPage(), dto.getPagesize());
        if (list == null || list.size() <= 0) {
            list = defaultList();
        }
        List<Long> userId = CollUtil.getFieldValues(list, "userId", long.class);
        Map<Long, UserInfo> map = userInfoApi.findAll(userId);
        List<TodayBest> todayBestList = new ArrayList<>();
        // for (RecommendUser recommendUser : list) {
        //     UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        //     TodayBest init = TodayBest.init(userInfo, recommendUser);
        //     todayBestList.add(init);
        // }
        for (RecommendUser recommendUser : list) {
            UserInfo userInfo = map.get(recommendUser.getUserId());
            TodayBest init = TodayBest.init(userInfo, recommendUser);
            todayBestList.add(init);
        }
        PageResult pageResult = new PageResult();
        pageResult.setPage(dto.getPage());
        pageResult.setPagesize(dto.getPagesize());
        pageResult.setItems(todayBestList);
        return pageResult;
    }

    public TodayBest todayBest() {
        RecommendUser recommendUser = recommendUserApi.queryWithMaxScore(UserHolder.getUserId());
        if (recommendUser == null) {
            recommendUser = new RecommendUser();
            recommendUser.setUserId(1l);
            recommendUser.setScore(99d);
        }
        UserInfo userInfo = userInfoApi.findById(recommendUser.getUserId());
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        return todayBest;
    }

    private List<RecommendUser> defaultList() {
        List list = new ArrayList();
        for (int i = 0; i < 10; i++) {
            RecommendUser recommendUser = new RecommendUser();
            recommendUser.setUserId(i + 1l);
            recommendUser.setScore(95d);
            list.add(recommendUser);
        }
        return list;
    }


    public TodayBest personalInfo(long userId) {
        UserInfo userInfo = userInfoApi.findById(userId);
        RecommendUser recommendUser = recommendUserApi.findById(userId, UserHolder.getUserId());
        Visitors visitors=new Visitors();
        visitors.setDate(System.currentTimeMillis());
        visitors.setFrom("首页");
        visitors.setUserId(userId);
        visitors.setVisitorUserId(UserHolder.getUserId());
        visitors.setVisitDate(new SimpleDateFormat("YYYYMMdd").format(new Date()));
        visitors.setScore(recommendUser.getScore());
        visitorsApi.save(visitors);
        return TodayBest.init(userInfo, recommendUser);
    }

    public String strangerQuestions(long userId) {
        Question question = questionApi.findByUserId(userId);
        return question == null ? "你喜欢java嘛?" : question.getTxt();
    }

    public void reply(Long id, String reply) {
        //{"userId":106,"huanXinId":"hx106","nickname":"黑马小妹",
        //    "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山？",
        //    "reply":"我喜欢秋天的落叶，夏天的泉水，冬天的雪地，只要有你一切皆可~"}
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        Map map = new HashMap();
        map.put("userId", UserHolder.getUserId());
        map.put("huanXinId", "hx" + UserHolder.getUserId());
        map.put("nickname", userInfo.getNickname());
        String s = strangerQuestions(id);
        map.put("strangerQuestion", s);
        map.put("reply", reply);
        String jsonString = JSON.toJSONString(map);
        huanXinTemplate.sendMsg("hx" + id, jsonString);
    }

    //附近的人
    public List<NearUserVo> search(String gender, String distance) {
        //查找附近的人的集合
        List<Long> userIds = userLocationApi.findSearch(UserHolder.getUserId(), distance);

        //userId集合查找map
        Map<Long, UserInfo> map = userInfoApi.findAll(userIds);
        //构造返回值集合
        List<NearUserVo> list = new ArrayList<>();
        //遍历取值
        for (long id : userIds) {
            //如果userId是用户本人,跳过
            if (id == UserHolder.getUserId()) {
                continue;
            }
            //根据userId取出userInfo
            UserInfo userInfo = map.get(id);
            //判断性别为空
            if (!StringUtils.isEmpty(gender)) {
                //判断是否相等
                if (!gender.equals(userInfo.getGender())) {
                    continue;
                }
            }
            NearUserVo vo = NearUserVo.init(userInfo);
            list.add(vo);
        }
        return list;
    }
}
